const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const UnauthorizedError = require('../utils/errors').UnauthorizedError;
const success = require('../utils/responses').success;
const failure = require('../utils/responses').failure;
const User = require('../models/user'); // 假设你有对应的 Mongoose 模型定义文件放在合适的位置

module.exports = async (req, res, next) => {
  try {
      const { token } = req.headers;

      if (!token) {
          throw new UnauthorizedError('当前接口需要认证才能访问');
      }

      const decoded = jwt.verify(token, process.env.SECRET);

      const { userId } = decoded;

      const user = await User.findById(userId);
      if (!user) {
          throw new UnauthorizedError('当前用户不存在');
      }

      if (user.role === 50) {
          throw new UnauthorizedError('您的账号已被封禁');
      }

      // if (user.role!== 100) {
      //   throw new UnauthorizedError('您没有权限使用当前接口');
      // }

      req.user = user;

      next();
  } catch (error) {
    console.log(error);
      failure(res, error);
  }
};